// ==========================================
// 数据迁移Java代码示例
// 将user_participation表中的attendees_data JSON字段迁移到user_participation_attendee表
// ==========================================

// 在UserParticipationController或单独的MigrationService中添加以下方法：

@Transactional
public void migrateAttendeesData() {
    log.info("开始迁移参会人数据...");
    
    // 1. 查询所有有attendees_data的user_participation记录
    String sql = "SELECT user_participation_id, attendees_data FROM user_participation WHERE attendees_data IS NOT NULL AND attendees_data != ''";
    Query query = entityManager.createNativeQuery(sql);
    List<Object[]> results = query.getResultList();
    
    int successCount = 0;
    int errorCount = 0;
    
    for (Object[] row : results) {
        Integer userParticipationId = (Integer) row[0];
        String attendeesDataStr = (String) row[1];
        
        try {
            // 2. 解析JSON数组
            JSONArray attendeesArray = JSON.parseArray(attendeesDataStr);
            
            if (attendeesArray != null && attendeesArray.size() > 0) {
                // 3. 先检查是否已经迁移过（避免重复）
                Map<String, String> checkQuery = new HashMap<>();
                checkQuery.put("user_participation_id", userParticipationId.toString());
                Query checkResult = attendeeService.select(checkQuery, new HashMap<>());
                List checkList = checkResult != null ? checkResult.getResultList() : null;
                
                if (checkList != null && checkList.size() > 0) {
                    log.info("user_participation_id {} 的参会人数据已存在，跳过", userParticipationId);
                    continue;
                }
                
                // 4. 插入每条参会人记录
                for (int i = 0; i < attendeesArray.size(); i++) {
                    JSONObject attendeeObj = attendeesArray.getJSONObject(i);
                    Map<String, Object> attendeeMap = new HashMap<>();
                    
                    attendeeMap.put("user_participation_id", userParticipationId);
                    attendeeMap.put("name", attendeeObj.getString("name"));
                    attendeeMap.put("email", attendeeObj.getString("email"));
                    attendeeMap.put("phone", attendeeObj.getString("phone"));
                    attendeeMap.put("phone_code", attendeeObj.getString("phoneCode") != null ? attendeeObj.getString("phoneCode") : "+86");
                    attendeeMap.put("affiliation", attendeeObj.getString("affiliation"));
                    attendeeMap.put("affiliation_en", attendeeObj.getString("affiliationEn"));
                    attendeeMap.put("title", attendeeObj.getString("title"));
                    attendeeMap.put("speech_title", attendeeObj.getString("speechTitle"));
                    attendeeMap.put("id_card", attendeeObj.getString("idCard"));
                    attendeeMap.put("wechat", attendeeObj.getString("wechat"));
                    attendeeMap.put("participation_type", attendeeObj.getString("participationType") != null ? attendeeObj.getString("participationType") : "onsite");
                    
                    // 处理 accommodation 字段（可能是boolean或字符串）
                    Object accObj = attendeeObj.get("accommodation");
                    if (accObj instanceof Boolean) {
                        attendeeMap.put("accommodation", ((Boolean) accObj) ? 1 : 0);
                    } else if (accObj instanceof String) {
                        String accStr = (String) accObj;
                        attendeeMap.put("accommodation", (accStr.equals("true") || accStr.equals("1") || accStr.equals("是")) ? 1 : 0);
                    } else {
                        attendeeMap.put("accommodation", 0);
                    }
                    
                    attendeeService.insert(attendeeMap);
                }
                
                successCount++;
                log.info("成功迁移 user_participation_id {} 的参会人数据，共 {} 条", userParticipationId, attendeesArray.size());
            }
        } catch (Exception e) {
            errorCount++;
            log.error("迁移 user_participation_id {} 的参会人数据失败", userParticipationId, e);
        }
    }
    
    log.info("迁移完成：成功 {} 条，失败 {} 条", successCount, errorCount);
}

// 注意：执行迁移前请先备份数据库！
// 迁移完成后，可以执行以下SQL删除attendees_data字段（可选）：
// ALTER TABLE user_participation DROP COLUMN attendees_data;


// 数据迁移Java代码示例
// 将user_participation表中的attendees_data JSON字段迁移到user_participation_attendee表
// ==========================================

// 在UserParticipationController或单独的MigrationService中添加以下方法：

@Transactional
public void migrateAttendeesData() {
    log.info("开始迁移参会人数据...");
    
    // 1. 查询所有有attendees_data的user_participation记录
    String sql = "SELECT user_participation_id, attendees_data FROM user_participation WHERE attendees_data IS NOT NULL AND attendees_data != ''";
    Query query = entityManager.createNativeQuery(sql);
    List<Object[]> results = query.getResultList();
    
    int successCount = 0;
    int errorCount = 0;
    
    for (Object[] row : results) {
        Integer userParticipationId = (Integer) row[0];
        String attendeesDataStr = (String) row[1];
        
        try {
            // 2. 解析JSON数组
            JSONArray attendeesArray = JSON.parseArray(attendeesDataStr);
            
            if (attendeesArray != null && attendeesArray.size() > 0) {
                // 3. 先检查是否已经迁移过（避免重复）
                Map<String, String> checkQuery = new HashMap<>();
                checkQuery.put("user_participation_id", userParticipationId.toString());
                Query checkResult = attendeeService.select(checkQuery, new HashMap<>());
                List checkList = checkResult != null ? checkResult.getResultList() : null;
                
                if (checkList != null && checkList.size() > 0) {
                    log.info("user_participation_id {} 的参会人数据已存在，跳过", userParticipationId);
                    continue;
                }
                
                // 4. 插入每条参会人记录
                for (int i = 0; i < attendeesArray.size(); i++) {
                    JSONObject attendeeObj = attendeesArray.getJSONObject(i);
                    Map<String, Object> attendeeMap = new HashMap<>();
                    
                    attendeeMap.put("user_participation_id", userParticipationId);
                    attendeeMap.put("name", attendeeObj.getString("name"));
                    attendeeMap.put("email", attendeeObj.getString("email"));
                    attendeeMap.put("phone", attendeeObj.getString("phone"));
                    attendeeMap.put("phone_code", attendeeObj.getString("phoneCode") != null ? attendeeObj.getString("phoneCode") : "+86");
                    attendeeMap.put("affiliation", attendeeObj.getString("affiliation"));
                    attendeeMap.put("affiliation_en", attendeeObj.getString("affiliationEn"));
                    attendeeMap.put("title", attendeeObj.getString("title"));
                    attendeeMap.put("speech_title", attendeeObj.getString("speechTitle"));
                    attendeeMap.put("id_card", attendeeObj.getString("idCard"));
                    attendeeMap.put("wechat", attendeeObj.getString("wechat"));
                    attendeeMap.put("participation_type", attendeeObj.getString("participationType") != null ? attendeeObj.getString("participationType") : "onsite");
                    
                    // 处理 accommodation 字段（可能是boolean或字符串）
                    Object accObj = attendeeObj.get("accommodation");
                    if (accObj instanceof Boolean) {
                        attendeeMap.put("accommodation", ((Boolean) accObj) ? 1 : 0);
                    } else if (accObj instanceof String) {
                        String accStr = (String) accObj;
                        attendeeMap.put("accommodation", (accStr.equals("true") || accStr.equals("1") || accStr.equals("是")) ? 1 : 0);
                    } else {
                        attendeeMap.put("accommodation", 0);
                    }
                    
                    attendeeService.insert(attendeeMap);
                }
                
                successCount++;
                log.info("成功迁移 user_participation_id {} 的参会人数据，共 {} 条", userParticipationId, attendeesArray.size());
            }
        } catch (Exception e) {
            errorCount++;
            log.error("迁移 user_participation_id {} 的参会人数据失败", userParticipationId, e);
        }
    }
    
    log.info("迁移完成：成功 {} 条，失败 {} 条", successCount, errorCount);
}

// 注意：执行迁移前请先备份数据库！
// 迁移完成后，可以执行以下SQL删除attendees_data字段（可选）：
// ALTER TABLE user_participation DROP COLUMN attendees_data;

